package com.bey.bow.web.video;

import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.bey.bow.entity.Video;
import com.bey.bow.service.video.VideoService;
import com.google.common.collect.Maps;

@Controller
@RequestMapping(value = "video")
public class VideoController {

	private static final int PAGE_SIZE = 5;

	private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("title", "标题");
	}

	private VideoService videoService;

	@RequestMapping(value = "")
	public String list(
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request) {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				request, "search_");

		Page<Video> videos = videoService.getVideos(pageNumber,
				PAGE_SIZE, sortType);

		model.addAttribute("videos", videos);
		model.addAttribute("sortType", sortType);
		model.addAttribute("sortTypes", sortTypes);
		model.addAttribute("searchParams", Servlets
				.encodeParameterStringWithPrefix(searchParams, "search_"));

		return "video/videoList";
	}

	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("video", videoService.getVideo(id));
		return "video/videoView";
	}

	@Autowired
	public void setVideoService(VideoService videoService) {
		this.videoService = videoService;
	}

}
